﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.Entity;
using System.Data;
using Home.Domain.Entities;
using Home.WebUI.Areas.Admin.Models;
using System.Transactions;
using Home.Utilities;
using Home.WebUI.Areas.Admin.Models.ProductViewModel;
using Home.WebUI.Models;
using Omu.ValueInjecter;
using Utilities;

namespace Home.WebUI.Areas.Admin.Controllers
{
    public class ProductController : Controller
    {
        private EFDbContext db = new EFDbContext();
        //
        // GET: /Admin/Product/

        public ActionResult Index(IndexViewModel model, int page = 1)
        {
            int totalItems = 0;//总项目数
            int pageSize = 5;
            var news = db.Products.Include(n => n.Category).Include(n => n.Brand).OrderByDescending(c => c.CreateDate).Skip((page - 1) * pageSize).Take(pageSize);
            totalItems = db.Products.Count();
            if (!string.IsNullOrEmpty(model.Search))
            {
                totalItems = db.Products.Where(c => c.Name.Contains(model.Search)).Count();
                news = news.Where(c => c.Name.Contains(model.Search));
            }
            model.Products = news;
            model.PagingInfo = new PagingInfo { CurrentPage = page, ItemsPerPage = pageSize, TotalItems = totalItems };
            return View(model);
        }
        public ActionResult Edit(int id)
        {
            Product model = db.Products.Find(id);
            return View(model);
        }
        [HttpPost]
        public ActionResult Edit(Product model, HttpPostedFileBase postFile)
        {
            if (ModelState.IsValid)
            {
                Product content = new Product();
                content.Id = model.Id;
                db.Products.Attach(content);
                content.InjectFrom<ConvertNoNull>(model);
                if (postFile!=null)
                {
                    bool chg = false;
                    string filename = "";
                    filename = Common.UpLoad(postFile, "img", 500, "/Upload/Product/", 1, ref chg);
                    if (!chg)
                    {
                        ModelState.AddModelError("Pic", filename);
                        return View(model);
                    }
                    content.Pic=filename;
                }
                #region 添加商品变动价格
		        ProductPrice price=new ProductPrice();
                price.CreateDate=DateTime.Now;
                price.ProductId=content.Id;
                price.Price=content.Price;
                db.ProductPrices.Add(price); 
	            #endregion
                db.SaveChanges();            
                return RedirectToAction("Index");
                
            }
            return View(model);
        }
        
        #region 分类
        public ActionResult Category(int? id = 0)
        {
            CategoryDropDownList(id);
            var model = db.Categorys.OrderByDescending(c => c.Sort).Include(c => c.ParentEntity);
            if (id == 0)
            {
                model = model.Where(c => c.ParentId == null);
            }
            else
            {
                model = model.Where(c => c.ParentId == id);
            }

            return View(model);
        }

        public ActionResult CategoryCreate()
        {
            BrandList();
            CategoryCreateDropDownList();
            return View();
        }
        [HttpPost]
        public ActionResult CategoryCreate(Category model, int[] brandId)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    int? sort = db.Categorys.Select(p => p.Sort).Min();
                    if (model.ParentId == 0)
                    {
                        model.ParentId = null;
                    }
                    model.Sort = sort == null ? 1 : sort - 1;
                    model.CreateDate = DateTime.Now;
                    model.State = 0;
                    //model.Path =
                    db.Categorys.Add(model);
                    db.SaveChanges();
                    #region 添加品牌
                    foreach (var item in brandId)
                    {
                        Category_Brand categorybrandmodel = new Category_Brand();
                        categorybrandmodel.BrandId = item;
                        categorybrandmodel.CategoryId = model.Id;
                        db.Category_Brands.Add(categorybrandmodel);
                    }
                    db.SaveChanges(); 
                    #endregion
                    return RedirectToAction("Category");
                }
            }
            catch (DataException)
            {
                TempData["Tip"] = new TipModel(0, "无法保存更改。再试一次，和如果问题仍然存在，请联系您的系统管理员");
            }
            BrandList(brandId);
            CategoryCreateDropDownList(model.ParentId);
            return View(model);
        }
        public ActionResult CategoryEdit(int id)
        {
            Category model = db.Categorys.Include(c=>c.Category_Brands).Single(c=>c.Id==id);
            CategoryCreateDropDownList(model.ParentId);
            BrandList(model.Category_Brands.Select(b => Convert.ToInt32(b.BrandId)).ToArray());
            return View(model);
        }
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult CategoryEdit(Category model, int[] brandId)
        {
            if (ModelState.IsValid)
            {
                if (model.ParentId == 0)
                {
                    model.ParentId = null;
                }
                //按需更新
                Category content = new Category();
                content.Id = model.Id;
                content.ParentId = -1;//无用值为了让其改变
                db.Categorys.Attach(content);
                content.InjectFrom(model);
                //ObjectMapperManager.DefaultInstance.GetMapper<Category, Category>().Map(model, content);//model的值传给content
                #region 更新品牌
                var selectedValue = new HashSet<int>();
                if (brandId != null)
                {
                    selectedValue = new HashSet<int>(brandId);//选中项
                }
                var category_Brands = db.Category_Brands.Where(c => c.CategoryId == model.Id);
                foreach (var item in category_Brands)
                {
                    //删除未选中的已有值
                    if (!selectedValue.Contains(Convert.ToInt32(item.BrandId)))
                    {
                        db.Category_Brands.Remove(item);
                    }
                }
                foreach (var item in selectedValue)
                {
                    //string[] input = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };
                    //int[] output = Array.ConvertAll<string, int>(input, delegate(string s)
                    //{
                    //    return int.Parse(s); 
                    //});
                    var BrandIds = new HashSet<int>(Array.ConvertAll<int?,int>(category_Brands.Select(c => c.BrandId).ToArray(),c=>Convert.ToInt32(c)));
                    if (!BrandIds.Contains(item))
                    {
                        Category_Brand addcategory_Brand = new Category_Brand();
                        addcategory_Brand.BrandId = item;
                        addcategory_Brand.CategoryId = model.Id;
                        db.Category_Brands.Add(addcategory_Brand);
                    }
                }

                #endregion
                if (db.SaveChanges() > 0)
                {
                    TempData["Tip"] = new TipModel(1, "修改成功");
                    return RedirectToAction("Category");
                }
            }
            BrandList(brandId);
            CategoryCreateDropDownList(model.ParentId);
            return View();
        }
        [HttpPost]
        public ActionResult CategoryDelete(int id)
        {
            try
            {
                // TODO: Add delete logic here    
                if (Request.IsAjaxRequest())
                {
                    Category content = db.Categorys.Find(id);
                    int newsNumer = db.Categorys.Count(n => n.ParentId == content.Id);
                    int brandNumber = db.Category_Brands.Count(c => c.CategoryId == content.Id);
                    //int newsNumer = content.News.Count();
                    //未做好不同提示
                    if (newsNumer > 0)
                    {
                        return Content(newsNumer.ToString());
                    }
                    if (brandNumber > 0)
                    {
                        return Content(brandNumber.ToString());
                    }
                    db.Categorys.Remove(content);
                    //EntityState stateafter = db.Entry(content).State;//Deleted状态     
                    int result = db.SaveChanges();
                    return Content("0");
                }
                else
                {
                    return Content("-1");
                }
            }
            catch
            {
                return Content("-1");
            }
        }
        /// <summary>
        /// 分类上移
        /// </summary>
        /// <param name="id">分类id</param>
        /// <param name="ParentId">分类的父类</param>
        /// <returns></returns>
        public ActionResult CategoryUp(int id, int ParentId=-1)
        {
            int? contentSort;//content的排序值，用于交换
            Category content = db.Categorys.Find(id);
            var where = db.Categorys.Where(c => c.Sort > content.Sort);
            if (ParentId!=-1)
            {
                where= where.Where(c => c.ParentId == ParentId);
            }
            else
            {
                where= where.Where(c => c.ParentId == null);
            }
            Category contentup = where.OrderBy(c => c.Sort).FirstOrDefault();
            if (contentup == null)
            {
                return Redirect(Request.UrlReferrer.ToString());
            }
            contentSort = content.Sort;
            db.Categorys.Attach(content);
            content.Sort = contentup.Sort;
            db.Categorys.Attach(contentup);
            contentup.Sort = contentSort;
            db.SaveChanges();
            return Redirect(Request.UrlReferrer.ToString());
        }
        //下架
        public ActionResult StateDown(int id)
        {
            Category content = new Category();
            content.Id = id;
            content.Name = "aaa";
            db.Categorys.Attach(content);
            content.State = 0;
            db.SaveChanges();
            return Redirect(Request.UrlReferrer.ToString()); 
        }
        //上架
        public ActionResult StateUp(int id)
        {
            Category content = new Category();
            content.Id = id;
            content.Name = "aaa";
            db.Categorys.Attach(content);
            content.State = 1;
            db.SaveChanges();
            return Redirect(Request.UrlReferrer.ToString());
        }
        /// <summary>
        /// 品牌复选值
        /// </summary>
        /// <param name="selecteds">选中的项，id值集合</param>
        public void BrandList(int[] selecteds=null)
        {
            var selectedValue = new HashSet<int>();
            if (selecteds!=null)
            {
                selectedValue = new HashSet<int>(selecteds.ToList());//选中项
            }
            
            var list = db.Brands.Select(b=>new{b.Name,b.Id});
           // SelectList items = new SelectList(list, "Id", "Name",);
            IList<SelectListItem> items = new List<SelectListItem>();
            foreach (var item in list)
            {
                items.Add(new SelectListItem { 
                    Text = item.Name, 
                    Value = item.Id.ToString(),
                    Selected=selectedValue.Contains(Convert.ToInt32(item.Id))//选中项是否包含
                });
            }
            ViewBag.Brand = items;
        }
        #endregion

        #region 品牌
        public ActionResult Brand()
        {
            return View(db.Brands.OrderByDescending(n => n.Sort).ToList());
        }

        public ActionResult BrandCreate()
        {
            return View();
        }
        [HttpPost]
        public ActionResult BrandCreate(Brand model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    int? sort = db.Brands.Select(p => p.Sort).Min();
                    model.Sort = sort == null ? 1 : sort - 1;
                    model.CreateDate = DateTime.Now;
                    db.Brands.Add(model);
                    db.SaveChanges();
                    return RedirectToAction("Brand");
                }
            }
            catch (DataException)
            {
                TempData["Tip"] = new TipModel(0, "无法保存更改。再试一次，和如果问题仍然存在，请联系您的系统管理员");
            }
            return View(model);
        }

        public ActionResult BrandEdit(int id)
        {
            return View(db.Brands.Find(id));
        }
        [HttpPost]
        public ActionResult BrandEdit(Brand model)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    Brand content = new Brand();
                    content.Id = model.Id;
                    db.Brands.Attach(content);
                    content.InjectFrom(model);
                    //ObjectMapperManager.DefaultInstance.GetMapper<Brand, Brand>().Map(model, content);//model的值传给content
                    db.SaveChanges();
                    TempData["Tip"] = new TipModel(1, "保存成功");
                    return RedirectToAction("Brand");
                }
            }
            catch (DataException)
            {
                TempData["Tip"] = new TipModel(0, "无法保存更改。再试一次，和如果问题仍然存在，请联系您的系统管理员");
            }
            return View(model);
        }

        public ActionResult BrandUp(int id)
        {
            int? contentSort;//content的排序值，用于交换
            Brand content = db.Brands.Find(id);
            var where = db.Brands.Where(c => c.Sort > content.Sort);
            Brand contentup = where.OrderBy(c => c.Sort).FirstOrDefault();
            if (contentup == null)
            {
                return Redirect(Request.UrlReferrer.ToString());
            }
            contentSort = content.Sort;
            db.Brands.Attach(content);
            content.Sort = contentup.Sort;
            db.Brands.Attach(contentup);
            contentup.Sort = contentSort;
            db.SaveChanges();
            return Redirect(Request.UrlReferrer.ToString());
        }
        [HttpPost]
        public ActionResult BrandDelete(int id)
        {
            try
            {
                // TODO: Add delete logic here    
                if (Request.IsAjaxRequest())
                {
                    #region 外键引用，有多少条其他表引用
                    int numberBrand = db.Products.Where(p => p.BrandId == id).Count();
                    if (numberBrand == 0)
                    {
                        numberBrand = db.Quotes.Where(q => q.BrandId == id).Count();
                    }
                    if (numberBrand == 0)
                    {
                        numberBrand = db.Category_Brands.Where(q => q.BrandId == id).Count();
                    }
                    if (numberBrand > 0)
                    {
                        return Content(numberBrand.ToString());
                    } 
                    #endregion
                    
                    Brand content = db.Brands.Find(id);
                    db.Brands.Remove(content);
                    //EntityState stateafter = db.Entry(content).State;//Deleted状态     
                    int result = db.SaveChanges();
                    return Content("0");
                }
                else
                {
                    return Content("-1");
                }
            }
            catch
            {
                return Content("-1");
            }
        }  
        #endregion

        /// <summary>
        /// 分类下拉
        /// </summary>
        /// <param name="selected">选中项</param>
        private void CategoryCreateDropDownList(object selected = null)
        {
            IList<Category> list = db.Categorys.OrderByDescending(p => p.Sort).Where(c=>c.ParentId==null).ToList();
            list.Insert(0, new Category() { Name = "添加为一级分类", Id = 0 });//添加默认第一列
            SelectList items = new SelectList(list, "Id", "Name", selected);

            ViewBag.Category = items;
        }
        /// <summary>
        /// 分类首页的分类下拉
        /// </summary>
        /// <param name="selected">选中项</param>
        private void CategoryDropDownList(object selected = null)
        {
            IList<Category> list = db.Categorys.OrderByDescending(p => p.Sort).Where(c => c.ParentId == null).ToList();
            list.Insert(0, new Category() { Name = "一级分类", Id = 0 });//添加默认第一列
            SelectList items = new SelectList(list, "Id", "Name", selected);
            ViewBag.Category = items;
        }
        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
